//vars




var DEFAULT_FPS = 30;

var DEFAULT_PLATFORM_HEIGHT = 13;
var DEFAULT_PLATFORM_WIDTH = 80;

var DEFAULT_ROLL_HEIGHT = 24;
var DEFAULT_ROLL_WIDTH = 24;

var DEFAULT_MIN_PLATFORM_INTERVAL = 50;
var DEFAULT_MAX_PLATFORM_INTERVAL = 100;

var DEFAULT_WORLD_SPEED = 3;
var DEFAULT_SPEED = 10;
var DEFAULT_ACCELERATE = 1;


var DEFAULT_ROLL_SPEED = 4;
var DEFAULT_BONUS_FALL_SPEED = 6;

var DEFAULT_WORLD_SPEED_ACCEL = 1;

var MINIMUM_SOLID_PLATFORMS = 2;

var DEFAULT_LIFES = 3;

var DEFAUL_AFTERDIE_VALUE = DEFAULT_FPS * 2;

var HEIGHT = 480;
var WIDTH = 320;

var DEFAULT_SCORE_NORMALIZER = 4000;

var DEFAULT_BONUS_HEIGHT = 16;
var DEFAULT_BONUS_WIDTH = 16;

var ROLL_MOVING_TYPE = {
	LEFT : {value: 1},
	RIGHT: {value: 2},
	NO   : {value: 0}
};

var DIFFICULTY_LEVELS = [ 0, 2000, 4000, 8000, 16000, 25000, Number.MAX_VALUE ];
var MAX_DIFFICULTY_LEVEL = DIFFICULTY_LEVELS.length - 1;

var PLATFORM_TYPE = {
	SOLID : {value: 1},
	KILLER: {value: 2},
	ICE   : {value: 3}
};

var SLIDE_PLATFORM_DIR = {
	LEFT: {value: 1},
	RIGHT: {value: 2}
};

var SLIDE_PLATFORM_SPEED = 2;

var BONUS_TYPE = {
	LIVE: {value: 1}
};

var DEFAULT_ICE_PLATFORM_LIFETIME = 35;

var ROLL_X_ACCELERATION_VALUE = 6.0;
var DEFAULT_ROLL_ACCEL_DEC = 0.4;

var DEFAULT_GRAVITY = 0.2;



function Polygon(coord) {
    this.coord = coord;
    this.color = "#CCCCCC"; 
}

Polygon.prototype.draw = function(ctx) {
    if (!this.coord || this.coord.length < 2) return;

    ctx.fillStyle = "rgb(23, 124, 255)";
    ctx.beginPath();
    var s = this.coord;
    ctx.moveTo(s[0], s[1]);
    for (var i = 2; i < s.length; i += 2) {
        ctx.lineTo(s[i], s[i + 1])
    }
    ctx.closePath();
    ctx.fill();
}

Polygon.prototype.move = function(dx, dy) {
    var s = this.coord;
    for (var i = 0; i < s.length-1; i += 1) {
        if (i%2 == 0) {
            s[i] += dx;
        } else {
            s[i] += dy;
        }
    }
    this.coord = s;
}
//MVC = model, view, ctrl





//model
function GModel() {
	var view = null;
	this.setView = function(v) { view = v; };
	this.getView = function() { return view; };


	this.init = function() {

		generateEnemies();

		lifes = DEFAULT_LIFES;

	};

	var pCounter = 0;
	var rollAccelX = 0.0;
	var rollAccelY = 0.0;

	var rollDie = false;
	var gameDifficultyLevel = 0;
	var level = 0;

	var shipMoveTop = false;
	var shipMoveBottom = false;
	var shipMoveLeft = false;
	var shipMoveRight = false;

    var deltaX = 0;
    var deltaY = 0;


	var score = 0;
	this.score = function() { return score; };

	var lifes = 0;
	this.lifes = function() { return lifes; };

	var platforms = { };
	this.platforms = function() { return platforms; };

	var ship = new Polygon() ;
	this.ship = function() { return ship; };

	var bonuses = { };
	this.bonuses = function() { return bonuses; };

	var roll = { };
	this.roll = function() { return roll; };

	var view = null;
	this.setView = function(v) { view = v; };
	this.getView = function() { return view; };

	var paused = false;
	this.paused = function() { return paused; };

	var afterdie = 0;
	this.afterdiePaused = function() { return afterdie > 0; };

	var speed = DEFAULT_SPEED;
	this.speed = function() { return speed; };
    
	var accelerate = DEFAULT_ACCELERATE;
	this.accelerate = function() { return accelerate; };




//	this.startMoveLeft = function() {
//		rollMoveLeft = true;
//	};
//
//	this.startMoveRight = function() {
//		rollMoveRight = true;
//	};
//
//	this.stopMoveRight = function() {
//		rollMoveRight = false;
//	};
//
//	this.stopMoveLeft = function() {
//		rollMoveLeft = false;
//	};

	this.tooglePause = function() {
		paused = !paused;
	};

	this.goMouse = function(e) {

        sacax=e.clientX;
        sacay=e.clientY;


	};

    this.startMoveLeft = function() {
		shipMoveLeft = true;
	};
    this.startMoveRight = function() {
		shipMoveRight = true;
	};
    this.startMoveTop = function() {
		shipMoveTop = true;
	};
    this.startMoveBottom = function() {
		shipMoveBottom = true;
	};
    this.stopMoveLeft = function() {
		shipMoveLeft = false;
	};
    this.stopMoveRight = function() {
		shipMoveRight = false;
	};
    this.stopMoveTop = function() {
		shipMoveTop = false;
	};
    this.stopMoveBottom = function() {
		shipMoveBottom = false;
	};

	var onLose = function() { return; }
	this.onLose = function(handler) { onLose = handler; };
	this.losed = function() { return lifes <= 0 && rollDie;}


	this.init = function() {

		generateEnemies();
		generateShip();

		lifes = DEFAULT_LIFES;

	};

    var intersect = function(obj, ship) {



//		do {
//			platforms[pCounter] = {
//				x: 100 + 100 * (Math.random() - 1),
//				y: 100 + 100 * (Math.random() - 1),
//				w: 10,
//				h: 10
//			};
//
//			pCounter++;
////		} while (platforms[pCounter - 1].x < (WIDTH));
//		} while (pCounter < 40)
	};



	// build next/new frame
	this.next = function() {

		if (paused) {
			view.update();
			return;
		}
        processEnemies();






   //     console.log (sacax + ' ' + sacay);



		if (shipMoveLeft) {
            deltaX = -1 * speed;
        }
        if (shipMoveRight) {
            deltaX = 1*speed;
        }
        if (shipMoveTop) {
            deltaY = -1 * speed;
        }
        if (shipMoveBottom) {
            deltaY = 1*speed;
        }
		if (!shipMoveLeft && !shipMoveRight) {
            deltaX = 0;
        }
		if (!shipMoveTop && !shipMoveBottom) {
            deltaY = 0;
        }

//        nextPosition = {x: ship.x + deltaX, y: ship.y + deltaY, w: ship.w, h: ship.h};
//        ship = nextPosition;
        ship.move(deltaX, deltaY);

        if (intersect(platforms, ship)) {
            aleft('бум')
        }
		view.update(); //update view

 	};
	var generateShip = function() {
        ship = new Polygon([100,100,130,160,100,430,630,330,100,130,100,100]);
//        ship = {
//                x: WIDTH/2,
//				y: HEIGHT/2,
//				w: 10,
//				h: 10
//
//        }
  	};
	var generateEnemies = function() {

		do {
			platforms[pCounter] = {
				x: 100 + 100 * (Math.random() - 1),
				y: 100 + 100 * (Math.random() - 1),
				w: 10,
				h: 10
			};

			pCounter++;
//		} while (platforms[pCounter - 1].x < (WIDTH));
		} while (pCounter < 40);


        platforms[0] = {
            x: 100 + 100 * (Math.random() - 1),
            y: 100 + 100 * (Math.random() - 1),
            w: 10,
            h: 10
        };
  	};



    var processEnemies = function() {

        for (var index in platforms) {
            var platform = platforms[index];

			if (platform.x > WIDTH || platform.y > HEIGHT) {
				delete platforms[index];
				generateEnemies();
				continue;
			}
            if(platform.x < WIDTH) { platform.x += 1; } else {   }
            if(platform.y < HEIGHT) { platform.y += 1; } else {   }

    }


    };
}

//view
function GView(resources) {


    var context = resources.CANVAS.getContext("2d");
	context.font = "bold 18px/2.8 arial";

	var FPS_REFRESH_INTERVAL = 10;

	var model = null;
	this.setModel = function(m) { model = m; };
	this.getModel = function() { return model; };

	var context = resources.CANVAS.getContext("2d");
	context.font = "normal 8px/2.8 arial";

	var bgPosition = 0;

	var frameCounter = 0;
	var lastTime = new Date().getTime();
	var totalTime = 0;


    this.play = function() {
//        alert('поехали');
        resources.CANVAS.style.display="block";
    };

	this.update = function() {

		if (model.paused()) {
			message("PAUSED");
			return;
		}

		if (model.losed()) {
			message("YOU LOSE");
			return;
		}

		if (model.afterdiePaused()) {
			return;
		}

		// draw background
//		bgPosition = (bgPosition - model.worldSpeed() <= -HEIGHT) ? 0 : bgPosition - model.worldSpeed();
//		context.drawImage(resources.BACKGROUND, 0, bgPosition, WIDTH, HEIGHT);
//		context.drawImage(resources.BACKGROUND, 0, bgPosition + HEIGHT, WIDTH, HEIGHT);

		// draw background
        context.fillStyle = "rgb(255, 255, 255)";
        context.fillRect(0,0,WIDTH,HEIGHT);

		// draw ship
		var ship = model.ship();

//				context.fillStyle = "rgb(255, 33, 123)";
//				context.fillRect(ship.x, ship.y, ship.w, ship.h);
        ship.draw(context);

		// draw platforms
		var platforms = model.platforms();
		for (var index in platforms) {
			var platform = platforms[index];
				context.fillStyle = "rgb(23, 124, 255)";
				context.fillRect(platform.x, platform.y, platform.w, platform.h);
		}
		// draw FPS
		var fps = (frameCounter / totalTime) * 1000.0;
        context.fillStyle = "rgb(0, 164, 216)";
		context.fillText(fps.toFixed(2) + " fps", 4, HEIGHT - 6);
		// calc FPS
		if (frameCounter > FPS_REFRESH_INTERVAL) { frameCounter = 0; totalTime  = 0; }
		frameCounter++;
		var currentTime = new Date().getTime();
		totalTime += (currentTime - lastTime);
		lastTime = currentTime;
	};

	this.clear = function() {
		context.clearRect(0, 0, WIDTH, HEIGHT);
	}
}

//ctrl
function KeyboardController() {
    var LEFT_KEY_CODE = 37;
	var RIGHT_KEY_CODE = 39;
    var TOP_KEY_CODE = 38;
	var BOTTOM_KEY_CODE = 40;
	var model = null;
	this.setModel = function(m) { model = m; };
	this.getModel = function() { return model; };
	this.onmousemove = function(event) {
        model.goMouse(event);
        
    };


	this.keydown = function(event) {
		if (event.keyCode == LEFT_KEY_CODE) {
			model.startMoveLeft();
		} else if (event.keyCode == RIGHT_KEY_CODE) {
			model.startMoveRight();
		} else if (event.keyCode == TOP_KEY_CODE) {
			model.startMoveTop();
		} else if (event.keyCode == BOTTOM_KEY_CODE) {
			model.startMoveBottom();
		} //else if (event.keyCode == PAUSE_KEY_CODE || event.keyCode == P_KEY_CODE) {
//			model.tooglePause();
//		}
	};

	this.keyup = function(event) {
		if (event.keyCode == LEFT_KEY_CODE) {
			model.stopMoveLeft();
		} else if (event.keyCode == RIGHT_KEY_CODE) {
			model.stopMoveRight();
		} else if (event.keyCode == TOP_KEY_CODE) {
			model.stopMoveTop();
		} else if (event.keyCode == BOTTOM_KEY_CODE) {
			model.stopMoveBottom();
		}
	};

	document.onkeydown = this.keydown;
	document.onkeyup = this.keyup;
    document.getElementById("canvas").onmousemove = this.onmousemove;
}
/**
 * Game class;
 *
 */


function Game(model, view, ctrl) {

    var self = this;

    view.setModel(model);
    ctrl.setModel(model);
    model.setView(view);

    var interrupter = null;


    model.onLose(
        function() {
            clearInterval(interrupter);

            var request = createXMLHttpRequest();

        }
    );


    this.play = function() {

        view.play();

        model.init();
        interrupter = setInterval(model.next, 1000 / DEFAULT_FPS);

    };



}





